<script setup lang="jsx">
import { ref } from 'vue';
import { Button, Tag } from 'ant-design-vue';
import { findNodesWithChildren, handleTree, parseTime } from '@/utils';
import { delDept, getDeptData } from '@/service/api';
import Modal from '@/components/common/modal.vue';
import Search from './modules/search.vue';
import AddForm from './modules/add.vue';

const searchParams = ref({
  deptName: null,
  status: null
});

const columns = ref([
  {
    key: 'deptName',
    dataIndex: 'deptName',
    title: '部门名称',
    width: 260,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'orderNum',
    dataIndex: 'orderNum',
    title: '排序',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.status === null) {
        return null;
      }

      const tagMap = {
        0: 'success',
        1: 'error'
      };

      const label = record.status == 0 ? '正常' : '异常';

      return <Tag color={tagMap[record.status] || 'error'}>{label}</Tag>;
    }
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '创建时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.createTime == null) {
        return null;
      }
      return parseTime(record.createTime);
    }
  },
  {
    key: 'cz',
    dataIndex: 'createTime',
    title: '操作',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <div>
          <Button type="link" size="small" onClick={() => add('edit', record)}>
            <icon-ic-round-edit class="align-sub text-icon" />
            修改
          </Button>
          <Button type="link" size="small" onClick={() => add('addChild', record)}>
            <icon-ic-round-add class="align-sub text-icon" />
            新增
          </Button>
          {record.parentId != 0 ? (
            <Button
              type="link"
              size="small"
              danger
              v-if={record.parentId !== 0}
              onClick={() => {
                deleteDept(record);
              }}
            >
              <icon-ic-round-delete class="align-sub text-icon" />
              删除
            </Button>
          ) : (
            ''
          )}
        </div>
      );
    }
  }
]);
const tableData = ref([]);
const loading = ref(false);
const defaultExpandedRowKeys = ref([]);

function getData() {
  loading.value = true;
  getDeptData(searchParams.value)
    .then(({ data, error }) => {
      if (!error) {
        tableData.value = handleTree(data, 'deptId');
        defaultExpandedRowKeys.value = findNodesWithChildren(tableData.value).map(item => item.deptId);
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

getData();
function deleteDept(row) {
  window.$modal.confirm({
    title: `是否确认删除名称为"${row.deptName}"的数据项？`,
    onOk: () => {
      delDept(row.deptId).then(({ data, error }) => {
        if (!error) {
          window.$message.success('删除成功');
          getData();
        }
      });
    }
  });
}

const currentRow = ref(null);
const operateType = ref('add');
const visible = ref(false);
const addFormRef = ref(null);
function add(type, row = null) {
  currentRow.value = row;
  operateType.value = type;
  visible.value = true;
}

function handleOk() {
  addFormRef.value.submitForm();
}

function handleClose() {
  visible.value = false;
  currentRow.value = null;
}

function handleSuccess() {
  getData();
  handleClose();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="getData()" @search="getData()" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="add('add')">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <ATable
        :columns="columns"
        :data-source="tableData"
        size="small"
        :loading="loading"
        :default-expanded-row-keys="defaultExpandedRowKeys"
        row-key="deptId"
        :default-expand-all-rows="true"
        :scroll="{ x: 'auto', y: 'auto' }"
        :pagination="false"
        class="h-full"
      />
    </ACard>

    <Modal
      v-model:visible="visible"
      :title="`${operateType == 'add' ? '新增' : '修改'}部门`"
      height="500px"
      width="650px"
      :destroy-on-close="true"
      @ok="handleOk"
      @close="handleClose"
    >
      <AddForm
        ref="addFormRef"
        :dept-options="tableData"
        :current-row="currentRow"
        :operate-type="operateType"
        @success="handleSuccess"
      />
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" @click="handleOk()">确定</AButton>
          <AButton @click="handleClose">取消</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style></style>
